#define  _CRT_SECURE_NO_WARNINGS
#include "ListNode.h"

void print(ListNode* phead)
{
	assert(phead);
	ListNode* pcur = phead;
	while (pcur != NULL)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
}

ListNode* BuyNewNode(SListDatatype x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	assert(newnode);
	newnode->next = NULL;
	newnode->data = x;

	return newnode;
}

void SListPushBack(ListNode** pphead, SListDatatype x)
{
	assert(pphead);
	if (*pphead == NULL)
	{
		*pphead = BuyNewNode(x);
	}
	else 
	{
		ListNode* pcur = *pphead;
		while (pcur->next != NULL)
		{
			pcur = pcur->next;
		}
		pcur->next = BuyNewNode(x);
	}
}

void SListPushFront(ListNode** pphead, SListDatatype x)
{
	assert(pphead);
	if (*pphead == NULL)
	{
		*pphead = BuyNewNode(x);
	}
	else
	{
		ListNode* pcur = *pphead;
		*pphead = BuyNewNode(x);
		(*pphead)->next = pcur;
	}
}

void SListPopBack(ListNode** pphead)
{
	assert(pphead && *pphead);
	ListNode* pcur = *pphead;
	if (pcur->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		ListNode* ptail = pcur->next;
		while (ptail->next != NULL)
		{
			pcur = ptail;
			ptail = ptail->next;
		}
		ptail->data = 0;
		free(ptail);
		ptail = NULL;
		pcur->next = NULL;
	}
}

void SListPopFront(ListNode** pphead)
{
	assert(pphead && *pphead);
	ListNode* pcur = *pphead;
	*pphead = pcur->next;
	pcur->data = 0;
	free(pcur);
	pcur = NULL;
}

ListNode* SListFind(ListNode** pphead, SListDatatype x)
{
	assert(pphead);
	ListNode* pcur = *pphead;
	while (pcur !=NULL )
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void SListInsertAfter(ListNode* pos, SListDatatype x)
{
	assert(pos);
	if (pos->next == NULL)
	{
		pos->next = BuyNewNode(x);
	}
	else
	{
		ListNode* ptail = pos->next;
		pos->next = BuyNewNode(x);
		pos->next->next = ptail;
	}

}

void SListEraseAfter(ListNode** pphead, ListNode* pos)
{
	assert(pos);
	if (pos->next == NULL)
	{
		SListPopBack(&pos);
	}
	else
	{
		ListNode* ptail = pos->next->next;
		free(pos->next);
		pos->next = ptail;
	}
}

void SListDestroy(ListNode** pphead)
{
	assert(pphead && *pphead);
	ListNode* pcur = *pphead;

	while (pcur)
	{
		ListNode* tmp = pcur;
		pcur = pcur->next;
		free(tmp);
		tmp = NULL;
	}
	*pphead = NULL;

}